import React, { useEffect, useRef, useState } from 'react';
import { View, StyleSheet, Animated, Image, Text } from 'react-native';
import { RootState } from '@/models/index';
import { connect, ConnectedProps } from 'react-redux';
import { RouteProp } from '@react-navigation/native'
import { RootStackParamList, ModalStackNavigation } from '@/navigator/index';
import { useHeaderHeight } from '@react-navigation/stack';
import { viewportHeight } from '@/utils/index';
import { BlurView } from '@react-native-community/blur';
import coverRight from '@/assets/cover-right.png';
import {
    PanGestureHandler,
    PanGestureHandlerStateChangeEvent,
    State,
    TapGestureHandler,
    NativeViewGestureHandler,
} from 'react-native-gesture-handler';
import Tab from './Tab';
import { IProgram } from '@/models/album';
import { NativeSyntheticEvent } from 'react-native';
import { NativeScrollEvent } from 'react-native';

const mapStateToProps = ({ album }: RootState) => {
    return {
        summary: album.summary,
        author: album.author,
        list: album.list,
    };
};

const connector = connect(mapStateToProps);

type ModelState = ConnectedProps<typeof connector>;

interface IProps extends ModelState {
    route: RouteProp<RootStackParamList, 'Album'>;
    navigation: ModalStackNavigation;
}
const HEADER_HEIGHT = 260;
const USE_NATIVE_DRIVER = true;

function Album(props: IProps) {
    const { route, summary, author } = props;
    const headerHeight = useHeaderHeight();
    const RANGE = [-(HEADER_HEIGHT - headerHeight), 0];
    const tapRef = useRef<TapGestureHandler>(null);
    const panRef = useRef<PanGestureHandler>(null);
    const nativeRef = useRef<NativeViewGestureHandler>(null);
    let translationY = new Animated.Value(0);
    const { title, image } = route.params.item;
    const [lastScrollYValue, setLastScrollYValue] = useState(0);
    const [translationYValue, setTranslationYValue] = useState(0);
    const onGestureEvent = Animated.event(
        [{ nativeEvent: { translationY: translationY } }],
        {
            useNativeDriver: USE_NATIVE_DRIVER,
        },
    );
    const lastScrollY = new Animated.Value(0);
    const translationYOffset = new Animated.Value(0);
    const reverseLastScrollY = Animated.multiply(
        new Animated.Value(-1),
        lastScrollY,
    );
    const translateY = Animated.add(
        Animated.add(translationY, reverseLastScrollY),
        translationYOffset,
    );
    useEffect(() => {
        const { dispatch, route, navigation } = props;
        const { id } = route.params.item;
        dispatch({
            type: 'album/fetchAlbum',
            payload: {
                id,
            },
        });
        // navigation.setParams({
        //     opacity: translateY.interpolate({
        //         inputRange: RANGE,
        //         outputRange: [1, 0],
        //     }),
        // });
    }, [])
    function renderHeader() {
        return <View style={[styles.header, { paddingTop: headerHeight }]}>
            <Image source={{ uri: image }} style={styles.background} />
            <BlurView
                blurType="light"
                blurAmount={10}
                style={StyleSheet.absoluteFillObject}
            />
            <View style={styles.leftView}>
                <Image source={{ uri: image }} style={styles.thumbnail} />
                <Image source={coverRight} style={styles.coverRight} />
            </View>
            <View style={styles.rightView}>
                <Text style={styles.title}>{title}</Text>
                <View style={styles.summary}>
                    <Text numberOfLines={1} style={styles.summaryText}>
                        {summary}
                    </Text>
                </View>
                <View style={styles.author}>
                    <Image source={{ uri: author.avatar }} style={styles.avatar} />
                    <Text style={styles.name}>{author.name}</Text>
                </View>
            </View>
        </View>
    }
    const onScrollDrag = Animated.event(
        [{ nativeEvent: { contentOffset: { y: lastScrollY } } }],
        {
            useNativeDriver: USE_NATIVE_DRIVER,
            listener: ({ nativeEvent }: NativeSyntheticEvent<NativeScrollEvent>) => {
                setLastScrollYValue(nativeEvent.contentOffset.y);
            },
        },
    );
    const onItemPress = (data: IProgram, index: number) => {
        console.log('Detail')
        const { navigation, dispatch, list, route } = props;
        const previousItem = list[index - 1];
        const nextItem = list[index + 1];
        dispatch({
            type: 'player/setState',
            payload: {
                previousId: previousItem ? previousItem.id : '',
                nextId: nextItem ? nextItem.id : '',
                title: data.title,
                thumbnailUrl: route.params.item.image,
                sounds: list.map(item => ({ id: item.id, title: item.title })),
            },
        });
        navigation.navigate('Detail', { id: data.id });
    };

    const onHandlerStateChange = ({ nativeEvent }: PanGestureHandlerStateChangeEvent) => {
        if (nativeEvent.oldState === State.ACTIVE) {
            let { translationY } = nativeEvent;
            translationY -= lastScrollYValue;
            translationYOffset.extractOffset();
            translationYOffset.setValue(translationY);
            translationYOffset.flattenOffset();
            translationY = 0;
            setTranslationYValue(translationYValue + translationY);
            let maxDeltaY = -RANGE[0] - translationYValue;
            if (translationYValue < RANGE[0]) {
                setTranslationYValue(RANGE[0]);
                Animated.timing(translationYOffset, {
                    toValue: RANGE[0],
                    useNativeDriver: USE_NATIVE_DRIVER,
                }).start();
                maxDeltaY = RANGE[1];
            } else if (translationYValue > RANGE[1]) {
                setTranslationYValue(RANGE[1]);
                Animated.timing(translationYOffset, {
                    toValue: RANGE[1],
                    useNativeDriver: USE_NATIVE_DRIVER,
                }).start();
                maxDeltaY = -RANGE[0];
            }
            if (tapRef.current) {
                const tap: any = tapRef.current;
                tap.setNativeProps({
                    maxDeltaY,
                });
            }
        }
    };
    return <TapGestureHandler ref={tapRef} maxDeltaY={-RANGE[0]}>
        <View style={styles.container}>
            <PanGestureHandler
                ref={panRef}
                simultaneousHandlers={[tapRef, nativeRef]}
                onGestureEvent={onGestureEvent}
                onHandlerStateChange={onHandlerStateChange}
            >
                <Animated.View
                    style={[
                        styles.container,
                        {
                            transform: [
                                {
                                    translateY: translateY.interpolate({
                                        inputRange: RANGE,
                                        outputRange: RANGE,
                                        extrapolate: 'clamp',
                                    }),
                                },
                            ],
                        },
                    ]}>
                    {renderHeader()}
                    <View style={{ height: viewportHeight - headerHeight }}>
                        <Tab
                            panRef={panRef}
                            tapRef={tapRef}
                            nativeRef={nativeRef}
                            onScrollDrag={onScrollDrag}
                            onItemPress={onItemPress}
                        />
                    </View>
                </Animated.View>
            </PanGestureHandler>
        </View>
    </TapGestureHandler>
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    header: {
        height: HEADER_HEIGHT,
        flexDirection: 'row',
        paddingHorizontal: 20,
        alignItems: 'center',
    },
    background: {
        ...StyleSheet.absoluteFillObject,
        backgroundColor: '#eee',
    },
    leftView: {
        marginRight: 26,
    },
    thumbnail: {
        width: 98,
        height: 98,
        borderColor: '#fff',
        borderWidth: StyleSheet.hairlineWidth,
        borderRadius: 8,
        backgroundColor: '#fff',
    },
    coverRight: {
        height: 98,
        position: 'absolute',
        right: -23,
        resizeMode: 'contain',
    },
    rightView: {
        flex: 1,
    },
    title: {
        color: '#fff',
        fontSize: 18,
        fontWeight: '900',
    },
    summary: {
        backgroundColor: 'rgba(0, 0, 0, 0.3)',
        padding: 10,
        marginVertical: 10,
        borderRadius: 4,
    },
    summaryText: {
        color: '#fff',
    },
    author: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    avatar: {
        height: 26,
        width: 26,
        borderRadius: 13,
        marginRight: 8,
    },
    name: {
        color: '#fff',
    },
});
export default connector(Album)